﻿/// <reference path="../Libs/class.js" />
/// <reference path="persister.js" />
/// <reference path="../Libs/jquery-2.0.2.js" />
/// <reference path="ui.js" />
define(["jquery", "class", "ui", "persister"], function ($, Class, ui, p) {

        var rootUrl = "http://localhost:22954/api/";
        var Controller = Class.create({
            init: function () {
                this.persister = p.get(rootUrl);
            },
            loadGameUI: function (selector) {
                ui.logoutButton(selector, this.persister.nickname());
            },
            loadUI: function (selector) {
                if (!this.persister.isUserLoggedIn()) {
                    this.loadLoginAndRegisterFormUI(selector);
                }
                else {
                    this.loadGameUI(selector);
                }
                this.attachUIEventHandlers(selector);
            },
            loadLoginAndRegisterFormUI: function (selector) {
                var loginFormHtml = ui.loginForm()
                $(selector).html(loginFormHtml);
            },
            loadGame: function (selector, gameId) {
                this.persister.game.field(gameId, function (gameField) {
                    var gameHtml = ui.gameField(gameField);
                    $(selector).html(gameHtml)
                });
            },
            attachUIEventHandlers: function (selector) {
                var mainContainer = $(selector);
                var self = this;

                mainContainer.on("click", "#show-login-button", function () {
                    mainContainer.find(".button.selected").removeClass("selected");
                    $(this).addClass("selected");
                    mainContainer.find("#login-form").show();
                    mainContainer.find("#register-form").hide();
                });
                mainContainer.on("click", "#show-register-button", function () {
                    mainContainer.find(".button.selected").removeClass("selected");
                    $(this).addClass("selected");
                    mainContainer.find("#register-form").show();
                    mainContainer.find("#login-form").hide();
                });

                mainContainer.on("click", "#login-button", function () {
                    var user = {
                        username: $("#tb-login-username").val(),
                        password: $("#tb-login-password").val()
                    }

                    self.persister.user.login(user, function () {
                        $(selector).html("");
                        self.loadGameUI(selector);
                    }, function (err) {
                        mainContainer.find("#error-messages").text(err.responseJSON.Message);
                    });
                    return false;
                });
                mainContainer.on("click", "#register-button", function () {
                    var user = {
                        username: $(selector).find("#tb-register-username").val(),
                        nickname: $(selector).find("#tb-register-nickname").val(),
                        password: $(selector + " #tb-register-password").val()
                    }
                    self.persister.user.register(user, function () {
                        self.loadGameUI(selector);
                    }, function (err) {
                        mainContainer.find("#error-messages").text(err.responseJSON.Message);
                    });
                    return false;
                });
                $("header").on("click", "#logout-button", function (e) {
                    self.persister.user.logout(function () {
                        $("#mrusenPEdal").remove("#mrusenPEdal");
                        self.loadLoginAndRegisterFormUI(selector);
                    }, function (err) {
                    });
                });

                mainContainer.on("click", "#open-games-container a", function () {
                    console.log(1);
                    $("#game-join-inputs").remove();
                    var html =
                        '<div id="game-join-inputs">' +
                            '<button id="join-game-button" class="blue">Join game</button>' +
                        '</div>';
                    $(this).after(html);
                });
                mainContainer.on("click", "#join-game-button", function () {
                    var game = {
                        gameId: $(this).parents("li").first().data("game-id")
                    };

                    self.persister.game.join(game, function (err) {
                        mainContainer.find("#error-messages").text(err.responseJSON.Message);
                    });
                });
                mainContainer.on("click", "#create-game-button", function () {
                    var game = {
                        title: $("#tb-create-title").val().toString(),
                    }

                    var password = $("#tb-create-pass").val();
                    if (password) {
                        game.password = password;
                    }
                    self.persister.game.create(game);
                });

                mainContainer.on("click", "#active-games-container li.game-status-full a.btn-active-game", function () {
                    var gameCreator = $(this).parent().data("creator");
                    var myNickname = self.persister.nickname();
                    if (gameCreator == myNickname) {
                        $("#btn-game-start").remove();
                        var html =
                            '<a href="#" id="btn-game-start" class="blue">' +
                                'Start' +
                            '</a>';
                        $(this).parent().append(html);
                    }
                });

                mainContainer.on("click", "#btn-game-start", function () {
                    var parent = $(this).parent();

                    var gameId = parent.data("game-id");
                    self.persister.game.start(gameId, function () {
                        mainContainer.find("#game-holder").html("<h2 style='margin-top: 50px; margin-left: 50px;'>The game has been started</h2>").fadeOut(2000);
                    }, function (err) {
                        mainContainer.find("#error-messages").text(err.responseJSON.Message);
                    });

                    return false;
                });

                mainContainer.on("click", ".btn-active-game, .btn-in-progress", function () {
                    console.log(1);
                    self.loadGame(selector, $(this).parent().data("game-id"));
                });

                mainContainer.on("click", ".unit", function () {
                    var row = this.parentNode.rowIndex;
                    var col = this.cellIndex;

                    var currentUnit = this;
                    //shit, no time.
                    $(".battleField").on("click", ".empty", function () {
                        var emptyRow = this.parentNode.rowIndex;
                        var emptyCol = this.cellIndex;

                        $(".battleField").children().children().eq(emptyRow).children().eq(emptyCol).append(currentUnit);

                        $('<td></td>').addClass('empty').text(" ").appendTo(".battleField");
                    });


                });
            },

            loadOpenGamesList: function (selector) {
                this.persister.game.open(function (games) {
                    var list = ui.openGamesList(games);
                    $(selector).html(list);
                });
            },

            loadHome: function (selector) {
                $(selector).html("");
            },

            loadActiveGamesList: function (selector) {
                this.persister.game.myActive(function (games) {
                    var list = ui.activeGamesList(games);
                    $(selector).html(list);
                });
            },
        });
        return {
            get: function () {
                return new Controller();
            }
        }

});